﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Security;

namespace OwnZTec.OwnZCraft.Common
{
    public static class Server
    {

        [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        public static void SendText(IntPtr hwnd, string keys)
        {
            if (hwnd != IntPtr.Zero)
            {
                if (SetForegroundWindow(hwnd))
                {
                    System.Windows.Forms.SendKeys.SendWait(keys);
                }
            }
        }

        public static bool ServerStatus()
        {
            var ipa = Dns.GetHostAddresses(ConfigurationManager.AppSettings["MCAddress"]);
            var ip = new IPEndPoint(ipa[0], Convert.ToInt32(ConfigurationManager.AppSettings["MCPort"]));

            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            try
            {
                sock.Connect(ip);
                sock.Close();

                return true;
            }
            catch
            {
                return false;
            }


        }

        public static bool IsJavaRunning()
        {
            return Process.GetProcesses().Any(clsProcess => clsProcess.ProcessName.Contains(ConfigurationManager.AppSettings["JavaAppName"]));
        }

        public static bool StopServer()
        {
            try
            {
                var javaProc = Process.GetProcesses().Where(clsProcess => clsProcess.ProcessName.Contains("cmd")).OrderBy(clsProcess => clsProcess.VirtualMemorySize64).FirstOrDefault();

                SendText(javaProc.MainWindowHandle, "stop" + (char)13);

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool ShutdownServer()
        {
            try
            {
                var javaProc = Process.GetProcesses().Where(clsProcess => clsProcess.ProcessName.Contains(ConfigurationManager.AppSettings["JavaAppName"])).OrderBy(clsProcess => clsProcess.VirtualMemorySize64).FirstOrDefault();

                if (javaProc != null)
                    javaProc.Kill();

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool StartServer()
        {
            try
            {
                var file = ConfigurationManager.AppSettings["ServerStartFile"];
                var directory = file.Substring(0, file.LastIndexOf('\\'));

                var javaProc = new Process
                                      {
                                          StartInfo =
                                          {
                                              FileName = file,
                                              WorkingDirectory = directory
                                          }
                                      };

                javaProc.Start();

                return true;
            }
            catch
            {
                return false;
            }
        }

        private static SecureString GetSecurePassword(string pwd)
        {
            var secStrig = new SecureString();

            pwd.ToCharArray().ToList().ForEach(secStrig.AppendChar);

            return secStrig;
        }
    }
}
